package com.zp.self.module.level_5_设计模式.创建型模式.Ⅱ_工厂方法.配置反射;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author ：by Zeng Peng
 * @date ：Created 2022/6/25 17:03
 * @description ：配置工厂
 */
public class ReflectFactory {
    public static Map<String,Coffee> coffeeMap = new HashMap<>();
    static {
        Properties properties = new Properties();
        InputStream in = ReflectFactory.class.getClassLoader().getResourceAsStream("bean.properties");
        try {
            properties.load(in);
            for (Map.Entry<Object, Object> entry : properties.entrySet()) {
                Class<?> aClass = Class.forName((String) entry.getValue());
                Coffee o = (Coffee)aClass.getDeclaredConstructor().newInstance();
                coffeeMap.put(entry.getKey().toString(),o);
            }
        } catch (Exception e) {
          throw new RuntimeException("初始化加载失败...",e);
        }
    }

    public static Coffee createCoffee(String type){
        Coffee coffee = coffeeMap.get(type);
        if(coffee==null)
            throw new RuntimeException("不支持的Coffee类型");
        return coffee;
    }
}
